package cn.wizzer.app.web.commons.ext.websocket.action.msg.group;

import cn.wizzer.app.sys.modules.services.SysSensitiveService;
import cn.wizzer.app.user.modules.models.GroupLogUserRelation;
import cn.wizzer.app.user.modules.models.enums.MsgTypeEnum;
import cn.wizzer.app.user.modules.models.enums.OprTypeEnum;
import cn.wizzer.app.user.modules.models.vo.ChatUserVO;
import cn.wizzer.app.user.modules.services.*;
import cn.wizzer.app.web.commons.ext.websocket.filter.TokenFilter;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyCache;
import cn.wizzer.app.web.commons.ext.websocket.main.result.ChatResult;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.util.JSONUtil;
import cn.wizzer.framework.util.param.Param;
import cn.wizzer.framework.util.param.Param4Map;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.apache.commons.lang3.EnumUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.List;
import java.util.Map;

@IocBean()
@NettyAction(uri = "/group/send", filters = {TokenFilter.class})
public class GroupSendAction extends BaseNettyAction {

    @Inject
    @Reference
    private GroupLogService groupLogService;
    @Inject
    @Reference
    private SysSensitiveService sensitiveService;

    @Override
    public Result action(Channel income,
                         @Param4Map(fields = {@Param(name = "groupId", required = true),
                                 @Param(name = "content", required = true),
                                 @Param(name = "type", required = true)}) JSONObject params) {
        ChatUserVO sendUser = NettyCache.globalGet(params.get("appid"));
        //发送消息 -> 添加群消息记录 -> 创建用户读取群消息记录
        Map<String, Object> map = groupLogService.groupSend(sendUser.getId(), params.getString("groupId"), sensitiveService.filter(params.getString("content")), EnumUtils.getEnum(MsgTypeEnum.class, params.getString("type")), OprTypeEnum.SENT, false);
        List<GroupLogUserRelation> groupLogUserRelations = JSONObject.parseArray(JSONObject.toJSONString(map.get("groupLogUserRelations")), GroupLogUserRelation.class);

        String content = JSONUtil.toJSONString(map.get("groupLog"));
        //给群里在线的用户发送提醒
        for (GroupLogUserRelation groupLogUserRelation : groupLogUserRelations) {
            ChatUserVO receiveUser = NettyCache.globalGet(groupLogUserRelation.getUserId());
            if (receiveUser != null) {
                NettyMsgUtil.send(receiveUser.getChannel(), ChatResult.MessageTypeEnum.USER, ChatResult.ActionEnum.SEND, sendUser, content);
            }
        }
        return Result.success("发送成功");
    }
}
